package com.spring.core.bean;

import com.spring.core.annotation.Service;
import com.spring.core.context.AbstractApplicationContext;
import com.spring.util.StringUtil;

/**
 * 组件工厂
 *
 * @author Zee
 * @version 1.0
 * @date 2021/10/13
 */
public class ComponentBean extends AbstractBean {


    @Override
    public void init(AbstractApplicationContext context) {
        System.out.println("初始化Bean: @Component @Service @Controller...");
        for (String className : context.getClassNames()) {
            try {
                Class<?> clazz = Class.forName(className);
                if (hasAnnotationComponent(clazz,false)) {
                    Object obj = clazz.newInstance();
                    //1.beanName默认首字母小写
                    String beanName = clazz.getSimpleName();
                    //2.beanName为自定义名称
                    if (clazz.isAnnotationPresent(Service.class)) {
                        Service service = clazz.getAnnotation(Service.class);
                        //如果自定义名称不为空则替换为自定义名称
                        if (!"".equals(service.value())) {
                            beanName = service.value();
                        }
                    }
                    context.getIoc().put(beanName, obj);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }


}
